package com.nebula.controller.portal;

import com.alibaba.fastjson.JSON;
import com.nebula.common.Const;
import com.nebula.common.Result;
import com.nebula.controller.BaseController;
import com.nebula.entity.User;
import com.nebula.service.IUserService;
import com.nebula.service.impl.UserServiceImpl;
import com.nebula.util.MD5Util;
import com.nebula.util.UUIDUtil;
import com.nebula.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CcccX
 */
@WebServlet(urlPatterns = "/user")
public class UserController extends BaseController {

    private final IUserService userService = new UserServiceImpl();

    public String login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Result result = userService.login(username, password, request);
        if (result.isSuccess()) {
            UserVo user = (UserVo) result.getData();
            //更新登录时间
            User user1 = new User();
            user1.setId(user.getId());
            user1.setUpdatedTime(new Date());
            userService.update(user1);

            request.getSession().setAttribute(Const.USER_INFO, user);
        }
        return Const.JSON + JSON.toJSONString(result);
    }

    public String logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.invalidate();
        return Const.JSON + JSON.toJSONString(Result.createBySuccess(request.getContextPath() + "/login.jsp"));
    }

    public String register(HttpServletRequest request, HttpServletResponse response) {
        String password = request.getParameter("password");
        String rePassword = request.getParameter("rePassword");
        ObjectMapper objectMapper = new ObjectMapper();
        if (StringUtils.isBlank(password)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("请输入密码"));
        }
        if (StringUtils.isBlank(rePassword)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("请输入确认密码"));
        }
        if (!password.equals(rePassword)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("两次密码不一致"));
        }
        IUserService userService = new UserServiceImpl();
        String username = request.getParameter("username");
        String realname = request.getParameter("realname");
        String gender = request.getParameter("gender");
        if (StringUtils.isBlank(username)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("请输入用户名"));
        }
        if (StringUtils.isNotBlank(userService.findByUsername(username).getId())) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("用户名已存在"));
        }
        if (StringUtils.isBlank(realname)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("请输入姓名"));
        }
        if (StringUtils.isBlank(gender)) {
            gender = "人妖";
        }
        User user = new User();
        user.setId(UUIDUtil.get32UUID());
        user.setUsername(username);
        user.setPassword(MD5Util.MD5EncodeUtf8(password));
        user.setRealname(realname);
        user.setGender(gender);
        user.setRoleId(1003);
        Date date = new Date();
        user.setCreatedTime(date);
        user.setUpdatedTime(date);

        int resultCount = userService.save(user);
        if (resultCount == 0) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("注册失败"));
        }
        request.getSession().setAttribute("forward", MD5Util.MD5EncodeUtf8(user.getId()));
        Map<String, String> map = new HashMap<>(1);
        map.put("userId", user.getId());
        return Const.JSON + JSON.toJSONString(Result.createBySuccess("注册成功", map));
    }

    public String checkPwd(HttpServletRequest request, HttpServletResponse response) {
        String pwd = request.getParameter("pwd");
        if (StringUtils.isBlank(pwd)) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("请输入密码"));
        }
        UserVo userVo = (UserVo) request.getSession().getAttribute(Const.USER_INFO);

        User user = userService.findById(userVo.getId());

        if (!user.getPassword().equals(MD5Util.MD5EncodeUtf8(pwd))) {
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("密码错误，验证失败"));
        }

        return Const.JSON + JSON.toJSONString(Result.createBySuccess());
    }

    public String update(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String realName = request.getParameter("realName");
        String gender = request.getParameter("gender");
        if (StringUtils.isBlank(gender) || StringUtils.isBlank(realName)) return null;

        switch (gender) {
            case "male":
                gender = "男";
                break;
            case "female":
                gender = "女";
                break;
            default:
                gender = "保密";
                break;
        }
        User user = new User();
        user.setId(id);
        user.setRealname(realName);
        user.setGender(gender);
        try {
            userService.update(user);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("保存失败"));
        }
    }

    public String updatePwd(HttpServletRequest request, HttpServletResponse response) {
        String oldPwd = request.getParameter("oldPwd");
        String newPwd = request.getParameter("newPwd");
        String id = request.getParameter("id");
        User user = userService.findById(id);
        if (!MD5Util.MD5EncodeUtf8(oldPwd).equals(user.getPassword())) {
            //旧密码错误
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("旧密码错误"));
        }
        User user1 = new User();
        user1.setId(id);
        user1.setPassword(MD5Util.MD5EncodeUtf8(newPwd));
        try {
            userService.update(user1);
            return Const.JSON + JSON.toJSONString(Result.createBySuccessMessage("修改成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return Const.JSON + JSON.toJSONString(Result.createByErrorMessage("修改失败"));
        }
    }
}
